package com.longrise.android.byjk.plugins.dealsituation.course.exercises;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.common.utils.DeviceUtils;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.BaseFrameView;

/**
 * Created by godliness on 2017/8/18.
 * 习题 （目前包括：课后习题，模拟测试题）
 * <p>
 * 根据mParams.mHasqa区分课后习题
 * 模拟测试题cwid，mHasqa为false
 * v1.3.7开始使用
 */

public class ExercisesActivity extends BaseActivity<ExercisesPresenter> implements ExercisesView,
        BaseFrameView.ReloadListener, View.OnClickListener {

    private final String TAG = "ExercisesActivity";

    private final String SAVE_URL = "save_url";

    private Toolbar mToolbar;

    private WebView mWebView;
    private WebSettings mWebSetting;
    private BaseFrameView mLoadView;

    private VideoParams mParams;
    private String mUrl;

    /**
     * webView加载状态
     */
    private boolean mLoadIsError;

    /**
     * 课后习题需要的
     */
    private final String mFirstFlag = "ex_ontest";
    private String mCurrentFlag = mFirstFlag;

    private ViewTag mViewTag;

    @Override
    public int getContentViewId(@Nullable Bundle sateState) {
        if (sateState != null) {
            onRestoreState(sateState);
        } else {
            getExtraData();
        }
        return R.layout.activity_exercises;
    }

    /**
     * mParams.mHasqa==true 表示课后习题
     */
    private void getExtraData() {
        Intent extraIntent = getIntent();
        mParams = extraIntent.getParcelableExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE);
    }

    @Override
    public void initView() {
        initTtile();
        initContentView();
        setWebSetting();
        regEvent(true);

        toRequest();

        Tracker_Google.getInstance().addGoogleScreenName(mParams.mHasqa ? "课后习题" : "模拟测试题");
    }

    private void setWebSetting() {
        mWebSetting = mWebView.getSettings();

        mWebSetting.setLoadWithOverviewMode(true);
        mWebSetting.setUseWideViewPort(true);
        mWebSetting.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        mWebSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSetting.setDomStorageEnabled(true);
        mWebSetting.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSetting.setAppCachePath(absolutePath);
        mWebSetting.setAllowFileAccess(true);
        mWebSetting.setAppCacheEnabled(true);
        mWebSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);

        mWebView.addJavascriptInterface(mPresenter, "bb");
    }

    /**
     * 如果url不为null&&"" 直接加载
     */
    private void toRequest() {
        if (TextUtils.isEmpty(mUrl)) {
            mPresenter.toRequest();
            return;
        }
        loadWeb();
    }

    private void initTtile() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onKeyDown(KeyEvent.KEYCODE_BACK, null);
            }
        });
    }

    private void setTitle(String title) {
        if (mToolbar != null) {
            mToolbar.setTitle(title);
        }
    }

    private void initContentView() {
        mWebView = (WebView) findViewById(R.id.webview_exercises);
        mLoadView = (BaseFrameView) findViewById(R.id.bfv_exercises);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dialog_tiku_cancel:
                ViewTag viewTag = (ViewTag) v.getTag();
                executeCancle(viewTag.mType, viewTag.mFinished);
                DialogUtil.getInstance().dismiss();
                break;

            case R.id.dialog_tiku_confirm:
                ViewTag viewTag1 = (ViewTag) v.getTag();
                executeConfrim(viewTag1.mType);
                DialogUtil.getInstance().dismiss();
                break;

            default:
                break;
        }
    }

    private class DWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }
    }

    private class CourseWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            view.post(new Runnable() {
                @Override
                public void run() {
                    showLoadingDialog();
                }
            });
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLoadIsError = true;
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
            view.post(new Runnable() {
                @Override
                public void run() {
                    if (mLoadIsError) {
                        onError();
                        return;
                    }
                    dismissLoadingDialog();
                    //获取当前currentFlg
                    if (mParams != null && mParams.mHasqa) {
                        splitTitle(view.getTitle());
                    }
                }
            });
        }

        private void splitTitle(String params) {
            String title[] = params.split("&");
            if (title != null && title.length > 1) {
                mCurrentFlag = title[1];
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    @Override
    public void onReload(View v) {
        toRequest();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(VideoConsts.VIDEO_PARAMS_PARCELABLE, mParams);
        outState.putString(SAVE_URL, mUrl);
    }

    @Override
    public VideoParams getParams() {
        return mParams;
    }

    @Override
    public void parse(String url) {
        if (isFinishing()) {
            return;
        }
        generateWebUrl(url);
        loadWeb();
    }

    @Override
    public void onError() {
        if (mLoadView != null) {
            mLoadView.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
            mLoadView.setVisibility(View.GONE);
        }
        mLoadIsError = true;
    }

    @Override
    public void getTitle(String title) {
        setTitle(title);
    }

    @Override
    public void onBack() {
        finish();
    }

    @Override
    public void msgShowTipsDialog(int type, String msg, int isfinish) {
        showMsgDialog(type, msg, isfinish);
    }

    @Override
    public void setDeviceInfoForGA() {
        if (mWebView != null) {
            mWebView.loadUrl("javascript:setDeviceInfoForGA('" + DeviceUtils.getVersionName() + "')");
        }
    }

    @Override
    public void showLoadingDialog() {
        if (mLoadView != null) {
            mLoadView.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
            mLoadView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void dismissLoadingDialog() {
        if (mLoadView != null) {
            mLoadView.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
            mLoadView.setVisibility(View.GONE);
        }
        mLoadIsError = false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return dispatchOnBack();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void regEvent(boolean isClick) {
        if (mLoadView != null) {
            mLoadView.setOnReloadListener(isClick ? this : null);
        }
        if (mWebView != null) {
            mWebView.setWebViewClient(isClick ? new CourseWebViewClient() : null);
        }
        if (mWebView != null) {
            mWebView.setWebChromeClient(isClick ? new DWebChromeClient() : null);
        }
    }

    /**
     * 根据hasqa判断是否为课后习题
     */
    private void generateWebUrl(String url) {
        if (mParams == null) {
            return;
        }
        boolean hasqa = mParams.mHasqa;
        if (hasqa) {
            mUrl = mPresenter.packageCwidTestUrl(url);
        } else {
            mUrl = mPresenter.packageSimTestUrl(url);
        }
    }

    private void loadWeb() {
        PrintLog.e(TAG, "mUrl: " + mUrl);
        if (mWebView != null) {
            mWebView.loadUrl(mUrl);
        }
    }

    private void onRestoreState(Bundle outState) {
        if (outState != null) {
            mParams = outState.getParcelable(VideoConsts.VIDEO_PARAMS_PARCELABLE);
            mUrl = outState.getString(SAVE_URL);
        }
    }

    /**
     * 分发back键 区分课后习题和模拟测试题
     */
    private boolean dispatchOnBack() {
        boolean hasqa = mParams.mHasqa;
        if (hasqa) {
            courseTestBack();
            return true;
        }
        //以下为模拟测试题 模拟测试题点击back事件调用该方法，生命周期由web控制返回是否关闭当前页面 closeSimulationTest()
        mWebView.loadUrl("javascript:rebackPRE()");
        PrintLog.e(TAG, "模拟测试题");
        return true;
    }

    /**
     * 课后习题back操作
     */
    private void courseTestBack() {
        if (!TextUtils.isEmpty(mCurrentFlag) && mCurrentFlag.equals("exit")) {
            onBack();
            return;
        }
        if (mWebView != null) {
            mWebView.loadUrl("javascript:$_$.checkBack('" + mCurrentFlag + "')");
        }
    }

    /**
     * js交互 需要时弹出该dialog
     */
    private void showMsgDialog(final int type, String msg, final int isfinish) {
        LayoutInflater inflater = getLayoutInflater();
        View v = inflater.inflate(R.layout.dialog_tiku_tips, null, false);
        TextView tvCancle = (TextView) v.findViewById(R.id.dialog_tiku_cancel);
        TextView textMsg = (TextView) v.findViewById(R.id.dialog_tiku_message);
        TextView tvConfrim = (TextView) v.findViewById(R.id.dialog_tiku_confirm);
        if (type == ExercisesPresenter.MSG_SHOW_TIPS_DIALOG) {
            tvCancle.setText(getString(R.string.fhjc));
            tvConfrim.setText(getString(R.string.qrtj));
        } else {
            tvCancle.setText(getString(R.string.fhjs));
            tvConfrim.setText(getString(R.string.jxzt));
        }
        textMsg.setText(msg);
        if (mViewTag == null) {
            mViewTag = new ViewTag();
        }
        mViewTag.mType = type;
        mViewTag.mFinished = isfinish;
        tvCancle.setTag(mViewTag);
        tvConfrim.setTag(mViewTag);
        tvCancle.setOnClickListener(this);
        tvConfrim.setOnClickListener(this);
        DialogUtil.getInstance().creatAlertDialog(this, v, 266, 171);
    }

    private static class ViewTag {
        public int mType;
        public int mFinished;
    }

    /**
     * dialog cancle按钮
     */
    private void executeCancle(int type, int isfinish) {
        if (mWebView == null) {
            return;
        }
        if (type == ExercisesPresenter.MSG_SHOW_TIPS_DIALOG) {
            mWebView.loadUrl("javascript:$_$.backCheck()");
            return;
        }
        if (isfinish == 0) {
            onBack();
            return;
        }
        mWebView.loadUrl("javascript:$_$.exitTest()");
    }

    /**
     * dialog confirm按钮
     */
    private void executeConfrim(int type) {
        if (mWebView == null) {
            return;
        }
        if (type == ExercisesPresenter.MSG_SHOW_TIPS_DIALOG) {
            mWebView.loadUrl("javascript:$_$.submitEnsured()");
        }
    }

    private void detachWebView() {
        if (mWebView != null) {
            ViewParent viewParent = mWebView.getParent();
            if (viewParent != null) {
                ((ViewGroup) viewParent).removeView(mWebView);
            }
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebSetting.setJavaScriptEnabled(false);
        }
    }

    @Override
    protected void onDestroy() {
        regEvent(false);
        detachWebView();
        super.onDestroy();
    }
}
